package com.juku2024.juku.messaging

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.text.TextUtils
import android.util.Log
import androidx.core.app.ActivityCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.MessagingAnalytics
import com.google.firebase.messaging.RemoteMessage
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.tools.SPUtil
import java.util.ArrayDeque
import java.util.Queue

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        try {
            LogC.e( "Message onMessageReceived " + remoteMessage.from)
            // 笔记模式屏蔽通知
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                return
            }

            val notification = remoteMessage.notification ?: return

            if (remoteMessage.data.isEmpty()) {
                Log.e( "Firebase Message -> ","没有videoId, 直接启动App0...")
                showMainNotification(notification)
                return
            }

            // Check if message contains a data payload.
            val videoIdStr = remoteMessage.data[Constants.AROUTER_KEY_VIDEO_ID]
            if (TextUtils.isEmpty(videoIdStr)) {
                Log.e( "Firebase Message -> ","没有videoId, 直接启动App1...")
                showMainNotification(notification)
                return
            }

            val videoId = videoIdStr?.toLongOrNull()?:0L
            if (videoId <= 0L) {
                Log.e( "Firebase Message -> ","没有videoId, 直接启动App2...")
                showMainNotification(notification)
                return
            }
            Log.e( "Firebase Message -> ","即将跳转到详情，videoId: $videoId")

            NotificationUtils.showVideoNotification(
                applicationContext,
                videoId,
                notification.title,
                notification.body,
                notification.imageUrl?.toString(),
                notification.channelId)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun handleIntent(intent: Intent?) {
        if (com.blankj.utilcode.util.AppUtils.isAppForeground()) {
            super.handleIntent(intent)
            return
        }
        if (intent == null) return
        val action = intent.action
        // Using if/else here instead of a switch to reduce code size
        if ("com.google.android.c2dm.intent.RECEIVE" == action || ACTION_DIRECT_BOOT_REMOTE_INTENT == action) {
            handleMessageIntent(intent)
        }
    }

    private val recentlyReceivedMessageIds: Queue<String> = ArrayDeque(10)

    private fun handleMessageIntent(intent: Intent) {
        val messageId = intent.getStringExtra(com.google.firebase.messaging.Constants.MessagePayloadKeys.MSGID)?:""
        if (!alreadyReceivedMessage(messageId)) {
            passMessageIntentToSdk(intent)
        }
    }

    private fun passMessageIntentToSdk(intent: Intent) {
        var messageType = intent.getStringExtra(com.google.firebase.messaging.Constants.MessagePayloadKeys.MESSAGE_TYPE)
        if (messageType == null) {
            messageType = com.google.firebase.messaging.Constants.MessageTypes.MESSAGE
        }
        when (messageType) {
            com.google.firebase.messaging.Constants.MessageTypes.MESSAGE -> {
                MessagingAnalytics.logNotificationReceived(intent)
                val uri = intent.extras
                if (uri != null) {
                    onMessageReceived(RemoteMessage(uri))
                }
            }
            else -> Log.w(com.google.firebase.messaging.Constants.TAG, "Received message with unknown type: $messageType")
        }
    }

    private fun alreadyReceivedMessage(messageId: String): Boolean {
        if (TextUtils.isEmpty(messageId)) {
            return false
        }
        if (recentlyReceivedMessageIds.contains(messageId)) {
            if (Log.isLoggable(com.google.firebase.messaging.Constants.TAG, Log.DEBUG)) {
                Log.d(com.google.firebase.messaging.Constants.TAG, "Received duplicate message: $messageId")
            }
            return true
        }
        // Add this message ID to the queue
        if (recentlyReceivedMessageIds.size >= 10) {
            recentlyReceivedMessageIds.remove()
        }
        recentlyReceivedMessageIds.add(messageId)
        return false
    }

    private fun showMainNotification(notification: RemoteMessage.Notification) {
        NotificationUtils.showMainNotification(
            applicationContext,
            notification.title,
            notification.body,
            notification.imageUrl?.toString(),
            notification.channelId)
    }

    override fun onNewToken(p0: String) {
        super.onNewToken(p0)
        LogC.e("token -> $p0")
    }

}